package com.test.ad.demo;

import static com.kwad.sdk.utils.bw.runOnUiThread;

import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.anythink.banner.api.ATBannerExListener;
import com.anythink.banner.api.ATBannerView;
import com.anythink.china.api.ChinaDeviceDataInfo;
import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.ATAdRevenueListener;
import com.anythink.core.api.ATAdStatusInfo;
import com.anythink.core.api.ATNetworkConfirmInfo;
import com.anythink.core.api.ATSDK;
import com.anythink.core.api.ATShowConfig;
import com.anythink.core.api.AdError;
import com.anythink.core.api.DeviceDataInfo;
import com.anythink.dlopt.api.ATAppDownloadListener;
import com.anythink.interstitial.api.ATInterstitial;
import com.anythink.interstitial.api.ATInterstitialAutoEventListener;
import com.anythink.interstitial.api.ATInterstitialAutoLoadListener;
import com.anythink.interstitial.api.ATInterstitialListener;
import com.anythink.nativead.api.ATNative;
import com.anythink.nativead.api.ATNativeAdView;
import com.anythink.nativead.api.ATNativeDislikeListener;
import com.anythink.nativead.api.ATNativeEventExListener;
import com.anythink.nativead.api.ATNativeMaterial;
import com.anythink.nativead.api.ATNativeNetworkListener;
import com.anythink.nativead.api.ATNativePrepareExInfo;
import com.anythink.nativead.api.ATNativePrepareInfo;
import com.anythink.nativead.api.ATNativeView;
import com.anythink.nativead.api.NativeAd;
import com.anythink.nativead.api.NativeAdInteractionType;
import com.anythink.nativead.unitgroup.api.CustomNativeAd;
import com.anythink.network.baidu.BaiduATCustomController;
import com.anythink.network.baidu.BaiduATInitManager;
import com.anythink.network.ks.KSATCustomController;
import com.anythink.network.ks.KSATInitManager;
import com.baidu.mobads.sdk.api.BDAdConfig;
import com.google.android.material.snackbar.Snackbar;
import com.kwad.sdk.api.KsCustomController;
import com.test.ad.demo.base.BaseActivity;
import com.test.ad.demo.bean.AdType;
import com.test.ad.demo.model.AdModel;
import com.test.ad.demo.util.AdCacheUtil;
import com.test.ad.demo.util.ClickTimer;
import com.test.ad.demo.util.DeviceInfoUtil;
import com.test.ad.demo.util.PlacementIdUtil;
import com.test.ad.demo.util.SDKUtil;
import com.test.ad.demo.util.SelfRenderViewUtil;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;

/**
 * 娱乐页：触发广告展示，并进入收益详情。
 * 具体广告展示仍复用现有 Activity（如 MainActivity、RewardVideoAdActivity 等）。
 */
public class EntertainmentFragment extends Fragment {

    private static final String TAG = EntertainmentFragment.class.getSimpleName();
    private View root;

    // 广告按钮
    private ConstraintLayout btnBanner;
    private ConstraintLayout btnNative;
    private ConstraintLayout btnInterstitial;
//    private ImageButton btnDetail;
    // 广告按钮

    // 横幅广告
    private TextView tvStats;
    private ATBannerView mBannerView;
    private FrameLayout mBannerContainer;
    // 横幅广告

    // 原生广告
    private ATNative mATNative;
    private NativeAd mNativeAd;
    private ATNativeView mATNativeView;
    private View mSelfRenderView;
    private View mPanel;
    private int adViewWidth;
    private int adViewHeight;
    private final List<String> mData = new ArrayList<>();
    private NativeVideoButtonAdapter buttonAdapter;
    // 原生广告

    //插屏广告
    private ATInterstitial mInterstitialAd;
    String mCurrentPlacementId;
    private Boolean isInterstitialAdShow = false;
    // 插屏广告

    private Boolean btnLoading = false; // 按钮loading
    private Toast mToast; // 成员变量，保存 Toast 对象

    private TextView tvBannerTitle;
    private TextView tvNativeTitle;
    private TextView tvInterstitialTitle;

    private CountDownTimer bannerTimer;
    private CountDownTimer nativeTimer;
    private CountDownTimer interstitialTimer;

    AdCacheUtil adCacheUtil = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_entertainment, container, false);
        root = v;
        ClickTimer.init(v.getContext());
        adCacheUtil = new AdCacheUtil(v.getContext());
        btnBanner = v.findViewById(R.id.btn_banner);
        btnNative = v.findViewById(R.id.btn_native);
        btnInterstitial = v.findViewById(R.id.btn_interstitial);
//        btnDetail = v.findViewById(R.id.btn_earnings_detail);
        tvBannerTitle = v.findViewById(R.id.tv_banner_title);
        tvNativeTitle = v.findViewById(R.id.tv_native_title);
        tvInterstitialTitle = v.findViewById(R.id.tv_interstitial_title);

        setNativeAdapter();
        initBtnListener();
        initBtnCountDown();

        getToDayAdCount();
        intATSDK();

        return v;
    }

    private void intATSDK() {
        String androidId = DeviceInfoUtil.getAndroidId(root.getContext());
        Map customMap = new HashMap<>();
        customMap.put("channel",androidId);
        customMap.put("sub_channel",androidId);
        ATSDK.initCustomMap(customMap); //  对全部Placement有效
        ATSDK.deniedUploadDeviceInfo(
                  DeviceDataInfo.MCC //移动网络代码
                , DeviceDataInfo.MNC //移动国家代码
                , DeviceDataInfo.INSTALLER //应用安装来源
                , ChinaDeviceDataInfo.MAC //MAC地址
                , ChinaDeviceDataInfo.SSID//SSID
                , ChinaDeviceDataInfo.IMSI//IMSI
        );
        KSATInitManager.getInstance().setKSATCustomController(new KSATCustomController() {
            /*
             * 是否允许快手SDK主动使用ICCID，默认true
             * */
            @Override
            public boolean getCanReadICCID() {
                return false;
            }

            /*
             * 是否允许快手SDK主动使用Mac地址，默认true
             * */
            @Override
            public boolean getCanReadMacAddress() {
                return false;
            }
            /*
             * 是否允许快手SDK主动使用附近wifi列表，默认true
             * */
            @Override
            public boolean getCanReadNearbyWifiList() {
                return false;
            }

            /*
             * 更多的隐私数据开光
             * 参考文档：https://p1-web.adkwai.com/udata/pkg/KS-Android-KSAdSDk/doc/4701b963d40a77bc0f45fd71d30b57da352.pdf
             * 下的&ldquo;3.5 隐私信息控制开关&rdquo;说明
             * */
            @Override
            public KsCustomController getKsCustomeController() {
                return new MyKsCustomController();
            }
        });
    }

    private void showError(String msg) {
        try {
            // 确保在UI线程执行
            if (getActivity() == null) return;

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 取消之前的Toast
                        if (mToast != null) {
                            mToast.cancel();
                        }

                        // 创建错误信息Dialog
                        showErrorDialog(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 备用方案：使用普通Toast
                        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
                    }
                }
            });
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    /**
     * 显示错误信息Dialog
     */
    private void showErrorDialog(String msg) {
        if (getActivity() == null) return;

        // 创建Dialog
        Dialog errorDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent_NoTitleBar);
        errorDialog.setContentView(R.layout.error_dialog);
        errorDialog.setCancelable(false); // 不允许点击外部关闭

        // 设置错误信息
        TextView errorText = errorDialog.findViewById(R.id.tv_error_message);
        if (errorText != null) {
            errorText.setText(msg);
        }

        // 显示Dialog
        errorDialog.show();

        // 5秒后自动关闭
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (errorDialog.isShowing()) {
                    errorDialog.dismiss();
                }
            }
        }, 5000);
    }

    private void makeText(String msg) {
        try {
            if (mToast != null) {
                mToast.cancel();
            }
            mToast = Toast.makeText(root.getContext(), msg, Toast.LENGTH_SHORT);
            mToast.show();
        } catch (Throwable t) {

        }
    }

    private void loadBannerAd() {
        if(!SDKUtil.isInitialized) {
            SDKUtil.initSDK(root.getContext());
        }
//        Toast.makeText(v.getContext(), "初始化横幅参数", Toast.LENGTH_SHORT).show();
        mBannerContainer = root.findViewById(R.id.banner_container);
//        tvStats = root.findViewById(R.id.tv_stats);

        mBannerView = new ATBannerView(root.getContext());
        mBannerView.setVisibility(View.VISIBLE);
        mBannerView.setAdRevenueListener(new AdRevenueListenerImpl());
        mBannerView.setBannerAdListener(new ATBannerExListener() {
            @Override
            public void onDeeplinkCallback(boolean isRefresh, ATAdInfo adInfo, boolean isSuccess) {
                Log.i(TAG, "onDeeplinkCallback:" + adInfo.toString() + "--status:" + isSuccess);
            }

            @Override
            public void onDownloadConfirm(Context context, ATAdInfo adInfo, ATNetworkConfirmInfo networkConfirmInfo) {
                Log.i(TAG, "onDownloadConfirm:" + adInfo.toString() + " networkConfirmInfo:" + networkConfirmInfo);
            }

            @Override
            public void onBannerLoaded() {
                Log.i(TAG, "onBannerLoaded");
                mBannerContainer.setVisibility(View.VISIBLE);
                ClickTimer.setIntervalSeconds("btn_banner", 720);
                ClickTimer.setIntervalSeconds("btn_native", 720);
                ClickTimer.setIntervalSeconds("btn_interstitial", 720);
                initBtnCountDown();
                btnLoading = false;
            }

            @Override
            public void onBannerFailed(AdError adError) {
                Log.i(TAG, "onBannerFailed: " + adError.getFullErrorInfo());
                ClickTimer.setIntervalSeconds("btn_banner", 300);
                initBtnCountDown();
                btnLoading = false;
                showError("code:[" + adError.getCode() + "] desc:[" +adError.getDesc() + "] platformMSG:[" + adError.getPlatformMSG());
            }

            @Override
            public void onBannerClicked(ATAdInfo entity) {
                Log.i(TAG, "onBannerClicked:" + entity.toString());
            }

            @Override
            public void onBannerShow(ATAdInfo entity) {
                Log.i(TAG, "onBannerShow:" + entity.toString());
            }

            @Override
            public void onBannerClose(ATAdInfo entity) {
                mBannerView.setVisibility(View.GONE);
                mBannerContainer.setVisibility(View.GONE);
                Log.i(TAG, "onBannerClose:" + entity.toString());
            }

            @Override
            public void onBannerAutoRefreshed(ATAdInfo entity) {
                Log.i(TAG, "onBannerAutoRefreshed:" + entity.toString());
            }

            @Override
            public void onBannerAutoRefreshFail(AdError adError) {
                Log.i(TAG, "onBannerAutoRefreshFail: " + adError.getFullErrorInfo());
                showError("code:[" + adError.getCode() + "] desc:[" +adError.getDesc() + "] platformMSG:[" + adError.getPlatformMSG());
            }
        });

        // 添加横幅视图到容器
        if (mBannerContainer != null && mBannerView != null) {
            mBannerContainer.addView(mBannerView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            showBannerAd();
        }
    }

    private void showBannerAd() {
        
        // 获取横幅广告位ID
        Map<String, String> bannerPlacements = PlacementIdUtil.getBannerPlacements(getActivity());
        String placementId = bannerPlacements.get("All");
        if (placementId == null || placementId.isEmpty()) {
            Log.e(TAG, "Banner placement ID not found");
            makeText("Banner placement ID not found");
            return;
        }
        
        // 设置广告位ID
        mBannerView.setPlacementId(placementId);
        ATBannerView.entryAdScenario(placementId, AdConst.SCENARIO_ID.BANNER_AD_SCENARIO);
        mBannerView.setShowConfig(getATShowConfig());

        // 设置广告尺寸
        int padding = dip2px(12);
        Map<String, Object> localMap = new HashMap<>();
        localMap.put(ATAdConst.KEY.AD_WIDTH, getResources().getDisplayMetrics().widthPixels - 2 * padding);
        localMap.put(ATAdConst.KEY.AD_HEIGHT, dip2px(60));
        mBannerView.setLocalExtra(localMap);

        // 设置自定义渲染（如果需要）
        mBannerView.setNativeAdCustomRender(new BaseActivity.NativeAdCustomRender(getActivity()));

        // 加载广告
        mBannerView.loadAd();
    }

    private void loadNativeAd() {
        if(!SDKUtil.isInitialized) {
            SDKUtil.initSDK(root.getContext());
        }
        mATNativeView = root.findViewById(R.id.native_ad_view);
        if (mATNative == null) {
            mATNative = new ATNative(root.getContext(), PlacementIdUtil.getListPlacementId(root.getContext()), new ATNativeNetworkListener() {
                @Override
                public void onNativeAdLoaded() {
                    Log.i(TAG, "native ad onNativeAdLoaded------------- ");
                    ClickTimer.setIntervalSeconds("btn_banner", 720);
                    ClickTimer.setIntervalSeconds("btn_native", 720);
                    ClickTimer.setIntervalSeconds("btn_interstitial", 720);
                    initBtnCountDown();
                    btnLoading = false;
                    showNativeAd();
                }

                @Override
                public void onNativeAdLoadFail(AdError adError) {
                    Log.e(TAG, "native ad onNativeAdLoadFail------------- " + adError.getFullErrorInfo());
                    ClickTimer.setIntervalSeconds("btn_native", 300);
                    initBtnCountDown();
                    btnLoading = false;
                    showError("code:[" + adError.getCode() + "] desc:[" +adError.getDesc() + "] platformMSG:[" + adError.getPlatformMSG());
                }
            });
        }

        mATNative.setAdSourceStatusListener(new BaseActivity.ATAdSourceStatusListenerImpl());

        adViewWidth = mATNativeView.getWidth() != 0 ? mATNativeView.getWidth() : getResources().getDisplayMetrics().widthPixels;
        adViewHeight = (int) (adViewWidth * (3 / 4f));

        Map<String, Object> localMap = new HashMap<>();
        localMap.put(ATAdConst.KEY.AD_WIDTH, adViewWidth);
        localMap.put(ATAdConst.KEY.AD_HEIGHT, adViewHeight);
        //localMap.put(TTATConst.NATIVE_AD_IMAGE_HEIGHT, 0);
        //localMap.put(GDTATConst.AD_HEIGHT, -2);
        mATNative.setLocalExtra(localMap);

        //load ad
        mATNative.makeAdRequest();

        Log.i(TAG, "native ad start to load ad------------- ");
    }

    private void showNativeAd() {
        NativeAd nativeAd = mATNative.getNativeAd(getATShowConfig());
        if (nativeAd != null) {
            if (mNativeAd != null) {
                mNativeAd.destory();
            }
            mNativeAd = nativeAd;

            mNativeAd.setAdRevenueListener(new AdRevenueListenerImpl());
            mNativeAd.setNativeEventListener(new ATNativeEventExListener() {
                @Override
                public void onDeeplinkCallback(ATNativeAdView view, ATAdInfo adInfo, boolean isSuccess) {
                    Log.i(TAG, "onDeeplinkCallback:" + adInfo.toString() + "--status:" + isSuccess);
                }

                @Override
                public void onAdImpressed(ATNativeAdView view, ATAdInfo entity) {
                    Log.i(TAG, "native ad onAdImpressed:\n" + entity.toString());
                }

                @Override
                public void onAdClicked(ATNativeAdView view, ATAdInfo entity) {
                    Log.i(TAG, "native ad onAdClicked:\n" + entity.toString());
                }

                @Override
                public void onAdVideoStart(ATNativeAdView view) {
                    Log.i(TAG, "native ad onAdVideoStart");
                }

                @Override
                public void onAdVideoEnd(ATNativeAdView view) {
                    Log.i(TAG, "native ad onAdVideoEnd");
                }

                @Override
                public void onAdVideoProgress(ATNativeAdView view, int progress) {
                    Log.i(TAG, "native ad onAdVideoProgress:" + progress);
                }
            });

            mNativeAd.setDislikeCallbackListener(new ATNativeDislikeListener() {
                @Override
                public void onAdCloseButtonClick(ATNativeAdView view, ATAdInfo entity) {
                    Log.i(TAG, "native ad onAdCloseButtonClick");
                    exitNativePanel();
                }
            });

            mATNativeView.removeAllViews();

            ATNativePrepareInfo mNativePrepareInfo = null;

            try {
                mNativePrepareInfo = new ATNativePrepareExInfo();
                //bindTTDislikeDialog(mATNativeView, mNativeAd);
                if (mNativeAd.isNativeExpress()) {
                    mNativeAd.renderAdContainer(mATNativeView, null);
                } else {
                    SelfRenderViewUtil.bindSelfRenderView(root.getContext(), mNativeAd.getAdMaterial(), mSelfRenderView, mNativePrepareInfo);
                    mNativeAd.renderAdContainer(mATNativeView, mSelfRenderView);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //下载类原生自渲染广告设置下载状态监听，更新CTA按钮文案
            if (!mNativeAd.isNativeExpress() && mNativeAd.getAdMaterial()
                    .getNativeAdInteractionType() == NativeAdInteractionType.APP_DOWNLOAD_TYPE && mNativePrepareInfo.getCtaView() != null && mNativePrepareInfo.getCtaView() instanceof TextView) {
                TextView ctaTextView = (TextView) mNativePrepareInfo.getCtaView();
                mNativeAd.setAdDownloadListener(new ATAppDownloadListener() {
                    @Override
                    public void onDownloadStart(ATAdInfo adInfo, long totalBytes, long currBytes, String fileName, String appName) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ctaTextView.setText("暂停下载");
                                System.out.print("onDownloadStart totalBytes:" + totalBytes + ",currBytes:" + currBytes + ",appName:" + appName);
                            }
                        });
                    }

                    @Override
                    public void onDownloadUpdate(ATAdInfo adInfo, long totalBytes, long currBytes, String fileName, String appName) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ctaTextView.setText("暂停下载");
                                System.out.print("onDownloadUpdate totalBytes:" + totalBytes + ",currBytes:" + currBytes + ",appName:" + appName);
                            }
                        });
                    }

                    @Override
                    public void onDownloadPause(ATAdInfo adInfo, long totalBytes, long currBytes, String fileName, String appName) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ctaTextView.setText("恢复下载");
                                System.out.print("onDownloadPause totalBytes:" + totalBytes + ",currBytes:" + currBytes + ",appName:" + appName);
                            }
                        });
                    }

                    @Override
                    public void onDownloadFinish(ATAdInfo adInfo, long totalBytes, String fileName, String appName) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ctaTextView.setText("立即安装");
                                System.out.print("onDownloadFinish totalBytes:" + totalBytes + ",appName:" + appName);
                            }
                        });
                    }

                    @Override
                    public void onDownloadFail(ATAdInfo adInfo, long totalBytes, long currBytes, String fileName, String appName) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ctaTextView.setText("开始下载");
                                System.out.print("onDownloadFail totalBytes:" + totalBytes + ",currBytes:" + currBytes + ",appName:" + appName);
                            }
                        });
                    }

                    @Override
                    public void onInstalled(ATAdInfo adInfo, String fileName, String appName) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ctaTextView.setText("打开应用");
                                System.out.print("onInstalled appName:" + appName);
                            }
                        });
                    }
                });
            }
            mNativeAd.prepare(mATNativeView, mNativePrepareInfo);
            mATNativeView.setVisibility(View.VISIBLE);
            mPanel.setVisibility(View.VISIBLE);
            initNativePanelButtonList(mNativeAd.getAdMaterial());
        } else {
            System.out.print("this placement no cache!");
        }
    }

    private void initNativePanelButtonList(ATNativeMaterial atNativeMaterial) {
        boolean isNativeExpress = true;
        if (mNativeAd != null) {
            isNativeExpress = mNativeAd.isNativeExpress();
        }

        if (isNativeExpress) {
            return;
        }

        ATAdInfo atAdInfo = mNativeAd.getAdInfo();
        int networkId = atAdInfo.getNetworkFirmId();


        String adType = atNativeMaterial.getAdType();
        if (Objects.equals(adType, CustomNativeAd.NativeAdConst.VIDEO_TYPE)) {
            switch (networkId) {
                case 8: //for GDT
                    mData.add(PanelAction.VOICE_CHANGE);
                    mData.add(PanelAction.VIDEO_RESUME);
                    mData.add(PanelAction.VIDEO_PAUSE);
                    mData.add(PanelAction.VIDEO_PROGRESS);
                    break;
//                case 15:
//                    //for CSJ
//                    mData.add(VideoAction.VOICE_CHANGE);
//                    break;
                case 22:    //for BaiDu
                case 28:    //for KuaiShou
                    mData.add(PanelAction.VIDEO_PROGRESS);
                    break;
                case 66: //for Adx
                case 67: //for Direct
                    mData.add(PanelAction.VOICE_CHANGE);
                    mData.add(PanelAction.VIDEO_RESUME);
                    mData.add(PanelAction.VIDEO_PAUSE);
                    mData.add(PanelAction.VIDEO_PROGRESS);
                    break;
                case 79: //for Vivo
                    mData.add(PanelAction.VIDEO_RESUME);
                    mData.add(PanelAction.VIDEO_PAUSE);
                    break;
            }
        }

        int nativeAdInteractionType = atNativeMaterial.getNativeAdInteractionType();
        if (nativeAdInteractionType == NativeAdInteractionType.APP_DOWNLOAD_TYPE) {
            switch (networkId) {
                case 8: //for GDT
                case 22:    //for BaiDu
                    mData.add(PanelAction.DOWNLOAD_STATUS);
                    mData.add(PanelAction.DOWNLOAD_PROGRESS);
                    break;
                case 66:    //for adx
                case 35:    //for myoffer
                case 41:    //for online
                case 42:    //for online
                case 43:    //for online
                case 44:    //for online
                case 79:    //for vivo
                    mData.add(PanelAction.DOWNLOAD_STATUS);
                    break;
            }
        }

        if (buttonAdapter != null) {
            buttonAdapter.notifyDataSetChanged();
        }
    }

    private void setNativeAdapter() {
        mPanel = root.findViewById(R.id.rl_panel);
        mSelfRenderView = root.findViewById(R.id.native_selfrender_view);
        RecyclerView rvButtonList = root.findViewById(R.id.rv_button);
        GridLayoutManager manager = new GridLayoutManager(root.getContext(), 2);
        rvButtonList.setLayoutManager(manager);
        final boolean[] isMute = new boolean[]{true};
        buttonAdapter = new NativeVideoButtonAdapter(mData, new NativeVideoButtonAdapter.OnNativeVideoButtonCallback() {
            @Override
            public void onClick(String action) {
                if (action.equals(PanelAction.VOICE_CHANGE)) {
                    if (mNativeAd != null) {
                        mNativeAd.setVideoMute(!isMute[0]);
                        isMute[0] = !isMute[0];
                    }
                } else if (action.equals(PanelAction.VIDEO_RESUME)) {
                    if (mNativeAd != null) {
                        mNativeAd.resumeVideo();
                    }
                } else if (action.equals(PanelAction.VIDEO_PAUSE)) {
                    if (mNativeAd != null) {
                        mNativeAd.pauseVideo();
                    }
                } else if (action.equals(PanelAction.VIDEO_PROGRESS)) {
                    if (mNativeAd != null) {
                        String tips = "video duration: " + mNativeAd.getVideoDuration() + ", progress: " + mNativeAd.getVideoProgress();
                        Log.i(TAG, tips);
                        Toast.makeText(root.getContext(), tips, Toast.LENGTH_LONG).show();
                    }
                } else if (action.equals(PanelAction.DOWNLOAD_STATUS)) {
                    if (mNativeAd != null) {
                        String tips = "download status: " + mNativeAd.getDownloadStatus();
                        Log.i(TAG, tips);
                        Toast.makeText(root.getContext(), tips, Toast.LENGTH_LONG).show();
                    }
                } else if (action.equals(PanelAction.DOWNLOAD_PROGRESS)) {
                    if (mNativeAd != null) {
                        String tips = "download progress: " + mNativeAd.getDownloadProgress();
                        Log.i(TAG, tips);
                        Toast.makeText(root.getContext(), tips, Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        rvButtonList.setAdapter(buttonAdapter);
    }

    private void exitNativePanel() {
        mData.clear();
        destroyNativeAd();
        mPanel.setVisibility(View.GONE);
    }

    private void destroyNativeAd() {
        if (mNativeAd != null) {
            mNativeAd.destory();
        }
    }

    private ATShowConfig getATShowConfig() {
        ATShowConfig.Builder builder = new ATShowConfig.Builder();
        builder.scenarioId(AdConst.SCENARIO_ID.BANNER_AD_SCENARIO);
        builder.showCustomExt(AdConst.SHOW_CUSTOM_EXT.BANNER_AD_SHOW_CUSTOM_EXT);
        return builder.build();
    }

    public int dip2px(float dipValue) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private void initBtnListener() {
        btnBanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if(ClickTimer.canClick("btn_banner") && !btnLoading) {
                   btnLoading = true;
                   loadBannerAd();
               } else {
                   if(btnLoading) {
                       makeText("操作频繁,请稍后再试");
                   } else {
                       Integer num = ClickTimer.getRemainingSeconds("btn_banner");
                       if(num > 0) {
                           initBtnCountDown();
                           makeText("请等待" + num + "秒后再试");
                       }
                   }
               }
            }
        });
        btnNative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(ClickTimer.canClick("btn_native") && !btnLoading) {
                    btnLoading = true;
                    loadNativeAd();
                } else {
                    if(btnLoading) {
                        makeText("操作频繁,请稍后再试");
                    } else {
                        Integer num = ClickTimer.getRemainingSeconds("btn_native");
                        if(num > 0) {
                            initBtnCountDown();
                            makeText("请等待" + num + "秒后再试");
                        }
                    }
                }
            }

        });
        btnInterstitial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ClickTimer.canClick("btn_interstitial") && !btnLoading) {
                    btnLoading = true;
                    loadInterstitialAd();
                } else {
                    if(btnLoading) {
                        makeText("操作频繁,请稍后再试");
                    } else {
                        Integer num = ClickTimer.getRemainingSeconds("btn_interstitial");
                        if(num > 0) {
                            initBtnCountDown();
                            makeText("请等待" + num + "秒后再试");
                        }
                    }
                }
            }
        });
//        btnDetail.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(getActivity(), EarningsActivity.class));
//            }
//        });
    }

    private void startCountdown(long millisInFuture, TextView tv, AdType t) {
        if(t == AdType.BANNER) {
            // 取消之前的倒计时
            if (bannerTimer != null) {
                bannerTimer.cancel();
            }

            bannerTimer = new CountDownTimer(millisInFuture, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    tv.setText("A（" + (millisUntilFinished / 1000) + "秒后再试）");
                }

                @Override
                public void onFinish() {
                    tv.setText("A");
                }
            };
            bannerTimer.start();
        }

        if(t == AdType.NATIVE) {
            // 取消之前的倒计时
            if (nativeTimer != null) {
                nativeTimer.cancel();
            }

            nativeTimer = new CountDownTimer(millisInFuture, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    tv.setText("B（" + (millisUntilFinished / 1000) + "秒后再试）");
                }

                @Override
                public void onFinish() {
                    tv.setText("B");
                }
            };
            nativeTimer.start();
        }

        if(t == AdType.INTERSTITIAL) {
            // 取消之前的倒计时
            if (interstitialTimer != null) {
                interstitialTimer.cancel();
            }

            interstitialTimer = new CountDownTimer(millisInFuture, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    tv.setText("C（" + (millisUntilFinished / 1000) + "秒后再试）");
                }

                @Override
                public void onFinish() {
                    tv.setText("C");
                }
            };
            interstitialTimer.start();
        }
    }

    private void getToDayAdCount() {

        TextView tvBannerText1 = root.findViewById(R.id.tv_banner_text1);
        TextView tvBannerText2 = root.findViewById(R.id.tv_banner_text2);
        TextView tvNativeText1 = root.findViewById(R.id.tv_native_text1);
        TextView tvNativeText2 = root.findViewById(R.id.tv_native_text2);
        TextView tvInterstitialText1 = root.findViewById(R.id.tv_interstitial_text1);
        TextView tvInterstitialText2 = root.findViewById(R.id.tv_interstitial_text2);

        // 获取今天的日期
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        String today = simpleDateFormat.format(new Date());


        List<AdModel> adList = adCacheUtil.getAdsByDate(today);
        Integer bannerCount = 0;
        Integer nativeCount = 0;
        Integer interstitialCount = 0;

        for (int i = 0; i < adList.size(); i++) {
            AdModel ad = adList.get(i);
            if(today.equals(ad.getDate().split(" ")[0])) {
                String text = ad.getDate().split(" ")[1] + " 成功加载";
                if(ad.getType() == AdType.BANNER) {
                    bannerCount += 1;
                    tvBannerText1.setText(text);
                } else if(ad.getType() == AdType.NATIVE) {
                    nativeCount += 1;
                    tvNativeText1.setText(text);
                } else if(ad.getType() == AdType.INTERSTITIAL) {
                    interstitialCount += 1;
                    tvInterstitialText1.setText(text);
                }
            }
        }
        tvBannerText2.setText("今日成功次数:" + bannerCount);
        tvNativeText2.setText("今日成功次数:" + nativeCount);
        tvInterstitialText2.setText("今日成功次数:" + interstitialCount);

    }

    private void initBtnCountDown() {
        Integer num1 = ClickTimer.getRemainingSeconds("btn_banner");
        Integer num2 = ClickTimer.getRemainingSeconds("btn_native");
        Integer num3 = ClickTimer.getRemainingSeconds("btn_interstitial");
        if(num1 > 0) {
            startCountdown(num1 * 1000,tvBannerTitle, AdType.BANNER);
        }
        if(num2 > 0) {
            startCountdown(num2 * 1000,tvNativeTitle, AdType.NATIVE);
        }
        if(num3 > 0) {
            startCountdown(num3 * 1000,tvInterstitialTitle, AdType.INTERSTITIAL);
        }
    }

    @Override
    public void onDestroyView() {
        if (mBannerContainer != null) {
            mBannerContainer.removeAllViews();
        }
        if (mBannerView != null) {
            mBannerView.destroy();
        }
        if (bannerTimer != null) {
            bannerTimer.cancel();
        }
        if (nativeTimer != null) {
            nativeTimer.cancel();
        }
        if (interstitialTimer != null) {
            interstitialTimer.cancel();
        }
        super.onDestroyView();
    }

    private void loadInterstitialAd() {
        if(!SDKUtil.isInitialized) {
            SDKUtil.initSDK(root.getContext());
        }
        Map<String, String>  mCurrentPlacements = PlacementIdUtil.getInterstitialPlacements(root.getContext());
        mCurrentPlacementId = mCurrentPlacements.get("All");
        mInterstitialAd = new ATInterstitial(root.getContext(), mCurrentPlacementId);
        mInterstitialAd.setAdRevenueListener(new AdRevenueListenerImpl());
        mInterstitialAd.setAdListener(new ATInterstitialListener() {
            @Override
            public void onInterstitialAdLoaded() {
                Log.e(TAG, "onInterstitialAdLoad:" + "ok");
                ClickTimer.setIntervalSeconds("btn_banner", 720);
                ClickTimer.setIntervalSeconds("btn_native", 720);
                ClickTimer.setIntervalSeconds("btn_interstitial", 720);
                initBtnCountDown();
//                ATInterstitial.entryAdScenario(mCurrentPlacementId, AdConst.SCENARIO_ID.INTERSTITIAL_AD_SCENARIO);
                showInterstitialAd();
                btnLoading = false;
            }

            @Override
            public void onInterstitialAdLoadFail(AdError adError) {
                //注意：禁止在此回调中执行广告的加载方法进行重试，否则会引起很多无用请求且可能会导致应用卡顿
                //AdError，请参考 https://docs.takuad.com/#/zh-cn/android/android_doc/android_test?id=aderror
                Log.e(TAG, "onInterstitialAdLoadFail:" + adError.getFullErrorInfo());
                ClickTimer.setIntervalSeconds("btn_interstitial", 300);
                initBtnCountDown();
                btnLoading = false;
                showError("code:[" + adError.getCode() + "] desc:[" +adError.getDesc() + "] platformMSG:[" + adError.getPlatformMSG());
            }

            @Override
            public void onInterstitialAdClicked(ATAdInfo atAdInfo) {
            }

            @Override
            public void onInterstitialAdShow(ATAdInfo atAdInfo) {
                //ATAdInfo可区分广告平台以及获取广告平台的广告位ID等
                //请参考 https://docs.takuad.com/#/zh-cn/android/android_doc/android_sdk_callback_access?id=callback_info
                //建议在此回调中调用load进行广告的加载，方便下一次广告的展示（不需要调用isAdReady()）
//                mInterstitialAd.load();
            }

            @Override
            public void onInterstitialAdClose(ATAdInfo atAdInfo) {
                isInterstitialAdShow = false;
            }

            @Override
            public void onInterstitialAdVideoStart(ATAdInfo atAdInfo) {

            }

            @Override
            public void onInterstitialAdVideoEnd(ATAdInfo atAdInfo) {
            }

            @Override
            public void onInterstitialAdVideoError(AdError adError) {
                //AdError，请参考 https://docs.takuad.com/#/zh-cn/android/android_doc/android_test?id=aderror
                Log.e(TAG, "onInterstitialAdVideoError:" + adError.getFullErrorInfo());
            }
        });
        mInterstitialAd.setAdSourceStatusListener(new BaseActivity.ATAdSourceStatusListenerImpl());

        Map<String, Object> localMap = new HashMap<>();

        mInterstitialAd.setNativeAdCustomRender(new BaseActivity.NativeAdCustomRender(root.getContext()));
        mInterstitialAd.setLocalExtra(localMap);
        mInterstitialAd.load();

    }

    private void showInterstitialAd() {
        if(isInterstitialAdShow == false) {
            isInterstitialAdShow = true;
            mInterstitialAd.show(getActivity(), getATShowConfig());
        } else {
            makeText("视频已加载~");
        }
    }

    private final ATInterstitialAutoLoadListener autoLoadListener = new ATInterstitialAutoLoadListener() {
        @Override
        public void onInterstitialAutoLoaded(String placementId) {
            Log.i(TAG, "PlacementId:" + placementId + ": onInterstitialAutoLoaded");
        }

        @Override
        public void onInterstitialAutoLoadFail(String placementId, AdError adError) {
            Log.i(TAG, "PlacementId:" + placementId + ": onInterstitialAutoLoadFail:\n" + adError.getFullErrorInfo());
        }

    };

    private final ATInterstitialAutoEventListener autoEventListener = new ATInterstitialAutoEventListener() {
        @Override
        public void onInterstitialAdClicked(ATAdInfo adInfo) {
            Log.i(TAG, "onInterstitialAdClicked:" + adInfo.toString());
        }

        @Override
        public void onInterstitialAdShow(ATAdInfo adInfo) {
            Log.i(TAG, "onInterstitialAdShow:" + adInfo.toString());
        }

        @Override
        public void onInterstitialAdClose(ATAdInfo adInfo) {
            Log.i(TAG, "onInterstitialAdClose:" + adInfo.toString());
        }

        @Override
        public void onInterstitialAdVideoStart(ATAdInfo adInfo) {
            Log.i(TAG, "onInterstitialAdVideoStart:" + adInfo.toString());
        }

        @Override
        public void onInterstitialAdVideoEnd(ATAdInfo adInfo) {
            Log.i(TAG, "onInterstitialAdVideoEnd:" + adInfo.toString());
        }

        @Override
        public void onInterstitialAdVideoError(AdError adError) {
            Log.i(TAG, "onInterstitialAdVideoError:" + adError.getFullErrorInfo());
        }

        public void onDeeplinkCallback(ATAdInfo adInfo, boolean isSuccess) {
            Log.i(TAG, "onDeeplinkCallback:\n" + adInfo.toString() + "| isSuccess:" + isSuccess);
        }

        public void onDownloadConfirm(Context context, ATAdInfo adInfo, ATNetworkConfirmInfo networkConfirmInfo) {
            Log.i(TAG, "onDownloadConfirm:\n" + adInfo.toString());
        }
    };


    // 广告收益监听器实现
    private class AdRevenueListenerImpl implements ATAdRevenueListener {
        @Override
        public void onAdRevenuePaid(ATAdInfo adInfo) {
            Log.i(TAG, "onAdRevenuePaid:" + adInfo.toString());
            double publisherRevenue = adInfo.getPublisherRevenue();
            String adType = adInfo.getFormat(); // "Native"、"Banner""Interstitial"
            DecimalFormat fm =  new DecimalFormat("#.##");
            double money = Double.valueOf(fm.format(publisherRevenue/2));
            if(adType.equals("Banner")) {
                adCacheUtil.insertAd(AdType.BANNER, money);
            } else if(adType.equals("Native")) {
                adCacheUtil.insertAd(AdType.NATIVE, money);
            } else if(adType.equals("Interstitial")) {
                adCacheUtil.insertAd(AdType.INTERSTITIAL, money);
            }

            // 显示收益提示框
            showRevenueDialog(money);
            getToDayAdCount();
        }
    }

    /**
     * 显示收益提示框
     */
    private void showRevenueDialog(double revenue) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    RevenueDialog dialog = new RevenueDialog(getActivity(), revenue);
                    dialog.show();
                }
            });
        }
    }
}


